package cc.lucien.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class HttpSessionListenerImpl implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        /*
         * ServletContextListener ServletContext的创建和销毁
         * ServletContextAttributeListener ServletContext域中属性变化的
         * HttpSessionListener   Session创建和销毁
         * HttpSessionAttributeListener  Session域中属性变化的
         * ServletRequestListener  Request的创建和销毁
         * ServletRequestAttributeListener Request域中属性变化的
         */
        HttpSession session = se.getSession();
        session.setMaxInactiveInterval(20);
        ServletContext application = se.getSession().getServletContext();
        Integer num = (Integer) application.getAttribute("onLineNum");
        if (num != null) {
            int count = num;
            count++;
            application.setAttribute("onLineNum", count);
        }else {
            application.setAttribute("onLineNum", 1);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext application = se.getSession().getServletContext();
        Integer num = (Integer) application.getAttribute("onLineNum");
        int count = num;
        count--;
        application.setAttribute("onLineNum", count);
        System.out.println(num);
    }
}
